package com.liangjie.uploadfull;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * 文件上传完整用法
 * 
 * @author LiangJie
 *
 */
@SuppressWarnings("serial")
public class CommonsUploadFull extends HttpServlet {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		// 设置文件大小限制
		upload.setFileSizeMax(30 * 1024 * 1024);
		upload.setSizeMax(50 * 1024 * 1024);
		if (upload.isMultipartContent(request)) {
			try {
				List<FileItem> list = upload.parseRequest(request);
				for (FileItem item : list) {
					//System.out.println(item.isFormField());
					if (item.isFormField()) {
						//System.out.println("进入isFormField");
						String filedName = item.getFieldName();
						String value = item.getString("utf-8");
						System.out.println("filedName-->" + filedName
								+ ",value-->" + value);
					} else {
						File file = new File(getServletContext().getRealPath(
								"/upload"), item.getName());
						item.write(file);
						item.delete();
					}
				}
			} catch (FileUploadException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
